package com.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.SingleThreadEventExecutor;

import java.util.Iterator;

/**
 * @author: sun.hongliang
 * @create: 2019/01/23 19:37
 */
@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf in = (ByteBuf) msg;
        System.out.println("Server received: " + in.toString(CharsetUtil.UTF_8));
        ctx.write(in);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //统计队列中的任务
        Iterator<EventExecutor> executorGroups = ctx.executor().parent().iterator();
        while (executorGroups.hasNext()) {
            SingleThreadEventExecutor executor = (SingleThreadEventExecutor) executorGroups.next();
            int tasksCount = executor.pendingTasks();
            if (executor == ctx.executor()) {
                System.out.println(ctx.channel() + " ---> " + executor + " pending size in queue is :" + tasksCount);
            } else {
                System.out.println(executor + " pending size in queue is :" + tasksCount);
            }
        }
        //统计代发的字节数
        long totalPendingWriteBytes = ctx.channel().unsafe().outboundBuffer().totalPendingWriteBytes();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ChannelFuture future = ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
        future.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                //写入完成回掉。
            }
        });

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
